from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.shortcuts import redirect
from .models import Article
from .models import Author
from django.core.paginator import Paginator
# 认证模块
from django.contrib import auth


# 对应数据库

from django.contrib.auth.hashers import make_password, check_password
from hashlib import md5
# Create your views here.


from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required

def index(request):
    # ?orderbytitle=0  正序
    # ?orderbytitle=1  倒叙来排
    # ?orderby_update_time=0  正序
    # ?orderby_update_time=1  倒叙来排

    rule_default = ['title', 'update_time']

    orderby_title = request.GET.get("orderbytitle", "0")
    orderby_update_time = request.GET.get("orderby_update_time", "0")

    if orderby_title == '0':
        rule_default[0] = "title"
    else:
        rule_default[0] = "-title"

    if orderby_update_time == '0':
        rule_default[1] = "update_time"
    else:
        rule_default[1] = "-update_time"
    print(rule_default)
    articles = Article.objects.order_by(*rule_default)

    page = request.GET.get('page', '1')
    try:
        page = int(page)
    except:
        page = 1
    # 将所有的数据进行分页,生成一个分页对象paginator
    paginator = Paginator(articles, 3)
    # 根据分页对象paginator 获取到某一页 page对象
    # paginator.num_pages
    pagex = paginator.get_page(page)
    print(pagex.number)
    print(pagex.has_previous())
    print(pagex.has_next())
    print(pagex.object_list)  # 本页的数据
    # print(pagex.next_page_number())
    key = request.GET.get("seacher", '')
    print(key)
    # test
    if key:
        # articles = Article.objects.raw("select * from Xblog_article where title like '%%{}%%'".format(key))
        articles = Article.objects.filter(title__contains=key)
        # articles = Article.objects.filter(title__regex='\d+')
        return render(request, 'result.html', {"articles": articles})

    article_type = request.GET.get("type", "")
    if article_type:
        articles = Article.objects.filter(article_type=article_type)
        return render(request, 'result.html', {"articles": articles})
    # return render(request, "index.html", {"articles": articles,'pagex':pagex})

    user = request.user

    return render(request, "index.html", {'pagex': pagex, 'hasnext': pagex.has_next(), 'user': user.username})


def add_article(request):
    if request.method == "GET":
        authors = Author.objects.all()
        print(authors)
        return render(request, "add_article.html", {"authors": authors})
    if request.method == "POST":
        # 获取到前端界面传过来的值
        title = request.POST.get("title", "")
        content = request.POST.get("content", "")
        articletype = request.POST.get("articletype", "")
        author = request.POST.get("author", "")

        # 向数据库中写入数据
        article = Article(title=title, content=content,
                          article_type=articletype,
                          author_id=author)
        article.save()
        return redirect("index")


# @login_required(login_url="/loginx/")
@login_required
def article_detail(request):
    id = request.GET.get("id")
    article = Article.objects.get(id=id)
    return render(request, "detail.html", {"article": article})


def update_article(request, articleid):
    if request.method == "GET":
        # todo
        article = Article.objects.get(id=articleid)
        return render(request, "update_article.html", {"article": article})

    if request.method == "POST":
        # 接收前端传过来的值   修改数据库的值

        try:
            id = request.POST.get("id")
        except Exception as e:
            id = articleid

        title = request.POST.get('title')
        content = request.POST.get('content')

        # 更新到数据库中
        article = Article.objects.get(id=id)
        article.title = title
        article.content = content
        article.save()

        return redirect("index")


def del_article(request, articleid):
    article = Article.objects.get(id=articleid)
    article.delete()

    return redirect("index")


def author_info(request):
    authorid = request.GET.get("authorid", "")
    print(authorid)
    author = Author.objects.get(id=authorid)
    print(author)
    print(author.name)
    articles = author.article_set.all()
    return render(request, 'author_info.html', {"author": author, "articles": articles})
    # return HttpResponse("作者界面")


def regist(request):
    if request.method == "GET":
        return render(request, 'regist.html')
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        # User.objects.create(username=username,password=password)
        User.objects.create_user(username=username, password=password)
        # User.objects.create_superuser(username=username,password=password)
        return redirect('loginx')
        # todo 延时 跳转



def loginx(request):
    if request.method == "GET":
        return render(request, 'loginx.html')

    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        user = authenticate(request, username=username, password=password)
        # print(user)
        # print(user.username)
        if user:
            login(request, user)
            return redirect("index")


def logoutx(request):
    logout(request)
    return redirect('loginx')